package com.frejoys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.frejoys.api.service.ApiAppService;
import com.frejoys.common.config.ValueConfig;
import com.frejoys.common.event.EventPublisher;
import com.frejoys.common.service.AliStorageService;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.dao.entity.StoreCode;
import com.frejoys.dao.entity.UserQrcode;
import com.frejoys.dao.mapper.OrderMapper;
import com.frejoys.dao.mapper.StoreCodeMapper;
import com.frejoys.listener.event.OrderQrCodeEvent;
import com.frejoys.listener.event.StoreQrCodeEvent;
import com.frejoys.listener.event.UserQrCodeEvent;
import com.frejoys.service.CommonService;
import com.frejoys.service.EventPublisherService;
import com.frejoys.service.StoreCodeService;
import com.frejoys.service.UserQrcodeService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

// 事件推送
@Service
@RequiredArgsConstructor
public class EventPublisherServiceImpl implements EventPublisherService {

    private final EventPublisher eventPublisher;

    private final RedissonClient redissonClient;

    private final CommonService commonService;

    private final OrderMapper orderMapper;

    private final AliStorageService aliStorageService;

    private final ApiAppService apiAppService;

    private final UserQrcodeService userQrcodeService;

    private final StoreCodeMapper storeCodeMapper;

    private final StoreCodeService storeCodeService;

    private final ValueConfig valueConfig;


    @Override
    public void sendOrderQrCodeService(Long orderSn) {
        eventPublisher.sendEvent(new OrderQrCodeEvent(orderSn));
    }

    @Override
    public void dispatchOrderQrCodeService(Long orderSn) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.orderQrcodeLockKey(orderSn));

        if (lock.tryLock()) {
            try {

                // 获取订单信息
                String qrCode = orderMapper.getQrCodeByOrderSn(orderSn);

                if (StrUtil.isEmpty(qrCode)) {
                    // 生成二维码
                    String qrFileName = aliStorageService.uploadQrCodeLogoImage(String.valueOf(orderSn));
                    if (StrUtil.isNotEmpty(qrFileName)) {
                        // 存储
                        if (!orderMapper.upQrCode(orderSn, qrFileName)) {
                            aliStorageService.deleteFileToOss(qrFileName);
                        }
                    }

                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }


    /**
     * 发送微信二维码到事件处理
     *
     * @param userId
     * @param site
     */
    @Override
    public void sendUserQrCodeService(Long userId, Integer site) {
        eventPublisher.sendEvent(new UserQrCodeEvent(userId, site));
    }

    /**
     * 处理用户二维码推送事件
     */
    @Override
    public void dispatchUserQrCodeService(Long userId, Integer site) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.userQrcodeLockKey(userId));

        if (lock.tryLock()) {
            try {

                // 获取用户二维码信息
                UserQrcode uq = userQrcodeService.getCodeInfo(userId);

                if (uq != null) {

                    // // 微信小程序码不存在
                    // if (StrUtil.isEmpty(uq.getWxCode())) {
                    //
                    //     // 获取微信小程序字节数组
                    //     byte[] bytes = apiAppService.getWxQrcodeByte(commonService.getWxAccessToken(site), String.valueOf(userId), 800);
                    //     // 存储微信小程序码
                    //     if (ArrayUtil.isNotEmpty(bytes)) {
                    //         if ((bytes.length / 1024) > 10) {
                    //
                    //             // 存储成小程序码
                    //             String fileName = aliStorageService.uploadFileToOss(new ByteArrayInputStream(bytes), null);
                    //             if (StrUtil.isNotEmpty(fileName)) {
                    //                 // 存储
                    //                 if (!userQrcodeService.upWxCode(userId, fileName)) {
                    //                     aliStorageService.deleteFileToOss(fileName);
                    //                 }
                    //             }
                    //
                    //         }
                    //     } else {
                    //         // 删除AccessToken
                    //         commonService.delWxAccessToken(site);
                    //     }
                    //
                    // }

                    // 二维码不存在
                    if (StrUtil.isEmpty(uq.getQrCode())) {

                        // 生成二维码
                        String qrFileName = aliStorageService.uploadQrCodeLogoImage(String.valueOf(userId));
                        if (StrUtil.isNotEmpty(qrFileName)) {
                            // 存储
                            if (!userQrcodeService.upQrCode(userId, qrFileName)) {
                                aliStorageService.deleteFileToOss(qrFileName);
                            }
                        }

                    }


                }


            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }


    }

    @Override
    public void sendStoreQrCodeService(Integer storeId, Integer type) {
        eventPublisher.sendEvent(new StoreQrCodeEvent(storeId, type));
    }

    @Override
    public void dispatchStoreQrCodeService(Integer storeId, Integer type) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.storePayQrcodeLockKey(storeId));

        if (lock.tryLock()) {
            try {

                // 获取店铺线上支付码
                StoreCode sc = storeCodeMapper.getCodeAndQrCode(storeId, type);
                if (sc != null && StrUtil.isEmpty(sc.getPayCode())) {

                    // 生成二维码
                    String qrFileName = aliStorageService.uploadQrCodeLogoImage(String.format(valueConfig.getStoreCodeUrl(), sc.getCode()));
                    if (StrUtil.isNotEmpty(qrFileName)) {
                        // 存储
                        if (!storeCodeService.upPayCode(storeId, type, qrFileName)) {
                            aliStorageService.deleteFileToOss(qrFileName);
                        }
                    }

                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

}